<template>
  <section class="message">
    <div class="message-box">
      <!--  头部  -->
      <div class="box-head">
        <div class="head-user">
          当前用户：{{ username }}
          <span class="status" v-if="isOnline">(在线)</span>
          <span class="status" v-else>(离线)</span>
        </div>
        <div class="head-chat" v-show="chatNameShow">正在和 {{toName}} 聊天</div>
      </div>

      <!--  主体内容   -->
      <div class="box-main">
        <!--  左部分    -->
        <div class="box-left">
          <!--  左上部分-未点击好友-空白聊天背景 -->
          <div class="left-nomessage" v-show="!isShowChat">
            <div class="nomessage-title">
              当前无聊天。请选择好友列表中的在线好友开始聊天吧！
            </div>
          </div>
          <!--   左上部分-消息聊天框   -->
          <div class="left-message" v-show="isShowChat">
            <div v-for="item in historyMessage">
              <!--左部分-对面消息-->
              <div class="msg-guest" v-if="item.fromName">
                <div class="msg-name">{{item.fromName}}</div>
                <div class="msg-content">
                  <img class="msg-img" src="../assets/img/avatar1.jpg" alt="">
                  <div class="message-1">{{item.message}}</div>
                </div>
              </div>
              <!--右边部分-自己消息-->
              <div class="msg-host" v-else>
                <div class="msg-name">{{username}}</div>
                <div class="msg-content">
                  <img class="msg-img" src="../assets/img/avatar2.jpg" alt="">
                  <div class="message-2">{{item.message}}</div>
                </div>
              </div>
            </div>
          </div>
          <!--   左下部分-消息发送框   -->
          <div class="left-input">
            <div class="input-wrapper">
              <n-input v-model:value="sendMessage.message" @keydown:enter="handleEnter" class="l-textarea" type="textarea" placeholder="在此输入文字信息,,," :autosize="{minRows: 3,maxRows: 5}"/>
              <n-button class="send-btn" type="success" size="small" @click="submit">
                发送
              </n-button>
            </div>
            <div class="send-tip">提示：Shift + Enter 换行</div>
          </div>
        </div>

        <!--   右部分   -->
        <div class="box-right">
          <!--   右上部分-好友列表   -->
          <div class="right-friend">
            <div class="right-title">
              <div>好友列表</div>
            </div>
            <div class="friend-list">
              <ul>
                <li v-for="item in friendList">
                  <div style="cursor: pointer" @click="showChat(item)">{{ item }}<span class="status"></span></div>
                </li>
              </ul>
            </div>
          </div>
          <!--   右下部分-广播列表(系统消息)   -->
          <div class="right-sys">
            <div class="right-title">
              <div>系统广播</div>
            </div>
            <div class="sys-msg">
              <ul>
                <li v-for="item in systemOfflineMessages">
                  {{item}}
                </li>
                <li v-for="item in systemMessages">
                  {{item}} 已上线
                </li>
              </ul>
            </div>
          </div>

        </div>
      </div>


    </div>
  </section>
</template>

<script setup lang="ts">

import {ref,onMounted} from "vue";
import {getCurrentUsername} from "@/api/home/api";
import {ChatMessage, ResponseData, SendMessage} from "@/api/type";
import { useMessage } from 'naive-ui'

const websocket = ref<WebSocket | null>();
const data = ref<ResponseData<string>>(); //初始化数据
const message = useMessage();

const username = ref<string | null>('');  // 当前用户
const isOnline = ref<boolean>(true);
const toName = ref<string | null>('');  // 聊天对象
const chatNameShow = ref<boolean>(false);  // 聊天对象是否显示

const friendList = ref<string[]>([]);  //在线好友列表
const systemOfflineMessages = ref<string[]>([]); //离线消息
const systemMessages = ref<string[]>([]);  //系统消息
const historyMessage = ref<ChatMessage[]>([]);  //聊天历史消息
const isShowChat = ref<boolean>(false);  //是否显示聊天框

/*message*/
const sendMessage = ref<SendMessage>({
  toName: '',
  message: '',
})

const handleEnter = (e: KeyboardEvent) =>{
  if(!e.shiftKey){
    e.preventDefault(); //阻止默认回车换行行为
    submit();
  }
}

function showChat (friend: string) {
  toName.value = friend;  // 聊天对象赋值

  //处理历史聊天信息
  const history = sessionStorage.getItem(toName.value);
  if(!history){
    historyMessage.value = [];
  } else {
    historyMessage.value = JSON.parse(history);  //反序列化获取历史聊天记录
  }

  isShowChat.value = true;  //渲染聊天
  chatNameShow.value = true;  //渲染正在和谁聊天
}

//发送信息
const submit = () =>{
  sendMessage.value.message = sendMessage.value.message.trim();
  if(!sendMessage.value.message){
    message.warning('请输入聊天内容');
    return;
  }
  //接收消息人
  sendMessage.value.toName = toName.value;
  //添加自己的一条信息
  historyMessage.value.push(JSON.parse(JSON.stringify(sendMessage.value)));
  //临时保存与该对象的聊天历史消息
  sessionStorage.setItem(toName.value, JSON.stringify(historyMessage.value))  //存字符串类型，序列化stringify,反序列化parse
  //向服务端发送信息
  websocket.value.send(JSON.stringify(sendMessage.value));
  sendMessage.value.message = '';
}

//onOpen
function onOpen() {
  isOnline.value = true;
}

const onClose = () => {
  isOnline.value = false;
}

//接收服务端发送的信息
const onMessage = (event: MessageEvent) =>{
  const dataString = event.data;  //服务端推送的信息
  console.log(dataString);
  const resJsonObj = JSON.parse(dataString);
  console.log(resJsonObj);
  //系统信息
  if(resJsonObj && resJsonObj.system){
    const names = resJsonObj.message;
    const offline = resJsonObj.offline;
    if(offline){
      systemOfflineMessages.value.push(resJsonObj.message);
    }else {
      for(let i=0; i<names.length; i++){
        if(names[i] !== username.value && !friendList.value.includes(names[i])){
          friendList.value.push(names[i]);
          systemMessages.value.push(names[i]);
        }
      }
    }
  }else {  //聊天信息
    //获取聊天记录
    const history = sessionStorage.getItem(resJsonObj.fromName);
    if(!history){
      historyMessage.value = [];
    }
    historyMessage.value.push(resJsonObj);
    sessionStorage.setItem(resJsonObj.fromName, JSON.stringify(historyMessage.value))
  }
}

//初始化
const init = async () => {
  await getCurrentUsername().then((res) =>{
    if(res.code === '200'){
      data.value = res;
      username.value = data.value.result;
    }
  }).catch((err)=>{
    console.log(err);
  });

  /*创建websocket对象*/
  websocket.value = new WebSocket('ws://localhost:8081/chat');

  websocket.value.onopen = onOpen;

  websocket.value.onmessage  = onMessage;

  websocket.value.onclose = onClose;

}

onMounted(()=>{
  init();
})

</script>

<style scoped>

.message {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.message-box {
  width: 50%;
  height: 700px;
  border: 1px solid #afdaaf;
  border-radius: 5px;
  overflow: hidden; /* 防止内部元素溢出 */
  box-shadow: 0 2px 8px rgba(157, 221, 157, 0.3);
}

.box-head {
  background-color: #afeaaf;
  height: 60px;
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start; /*子元素靠顶部对齐，防止拉伸挤压*/

  .head-user {
    font-size: 16px;
    font-weight: 600;
    margin-top: 5px;

    .status {
      font-size: 12px;
      font-weight: 500;
      margin-left: 5px;
      color: #0c8fe1;
    }
  }

  .head-chat {
    text-align: center;
    font-size: 18px;
    font-weight: 600;
  }
}

/*主体内容*/
.box-main {
  height: calc(100% - 60px);
  display: flex;

  .box-left {
    height: 100%;
    width: 70%;
    border-right: 1px solid #c2c3c5;

    display: flex;
    flex-direction: column;

    /*左侧无消息*/
    .left-nomessage {
      flex: 1;
      padding: 15px;
      overflow-y: auto;  /*内容过多下滑*/
      background-color: #fff;

      .nomessage-title {
        color: #eae5e5;
        font-size: 15px;
        font-weight: 500;
        line-height: 25px;
        background-color: #9e9c9c;
        padding: 5px 10px;
      }
    }

    /*左侧消息*/
    .left-message {
      flex: 1;
      padding: 15px;
      overflow-y: auto;  /*内容过多下滑*/
      background-color: #fff;

      .msg-guest {
        margin-bottom: 12px;
        padding: 0 5px;
        text-align: left;

        .msg-name {
          font-size: 14px;
          color: #000000;
          font-weight: 400;
          line-height: 25px;
        }

        .msg-content {
          display: flex;
          align-items: flex-start;

          .msg-img {
            width: 36px;
            height: 36px;
            border-radius: 5px;
          }
          .message-1 {
            margin-left: 10px;
            background-color: #f0f0f0;
            padding: 8px 12px;
            border-radius: 8px;
            max-width: 70%; /* 限制气泡最大宽度 */
          }

        }

      }

      .msg-host {
        margin-bottom: 12px;
        padding: 0 5px;
        text-align: right;

        .msg-name {
          font-size: 14px;
          color: #000000;
          font-weight: 400;
          line-height: 25px;
        }
        .msg-content {
          display: flex;
          align-items: flex-start;
          flex-direction: row-reverse;  /*反转*/

          .msg-img {
            width: 36px;
            height: 36px;
            border-radius: 5px;
            margin-left: 10px;
          }
          .message-2 {
            background-color: #beedc6;
            padding: 8px 12px;
            border-radius: 8px;
            max-width: 70%;
          }
        }
      }
    }

    /*左侧输入框*/
    .left-input {
      display: flex;
      flex-direction: column;
      padding: 12px 15px;
      border-top: 1px solid #c2c3c5;

      .input-wrapper {
        position: relative;
        flex: 1;

        .l-textarea {
          width: 100% !important; /*确保输入框占满容器*/
          padding-bottom: 50px !important; /*给下侧按钮预留空间*/
        }

        .send-btn {
          position: absolute;
          bottom: 8px;
          right: 8px;
          padding: 10px 30px;
        }

      }

      .send-tip {
        margin-top: 5px;
        color: #c2c3c5;
      }


    }
  }
  .box-right {
    width: 30%;
    height: 100%;
    /*处理子容器分布*/
    display: flex;
    flex-direction: column;

    .right-title {
      font-size: 16px;
      font-weight: 500;
      padding: 8px 10px;
      border-bottom: 1px solid #c2c3c5;
    }

    .right-friend {
      height: 40%;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .friend-list {
        flex: 1;
        overflow-y: auto;
        padding: 8px 10px;
      }

    }

    .right-sys {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .sys-msg {
        flex: 1;
        overflow-y: auto;
        padding: 8px 10px;
      }
    }

    .friend-list ul,.sys-msg ul {
      margin: 0;
      padding: 0;
      list-style: none;
    }


  }

}

</style>